package com.kyzh.core.pager.weal.live

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.gushenge.atools.util.AView
import com.gushenge.atools.util.setMargins
import com.gushenge.core.beans.LiveRoomInfo
import com.gushenge.core.beans.RoomGift
import com.gushenge.core.dao.MMKVConsts.uid
import com.kyzh.core.R
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.requests.LiveRequest
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.databinding.ActivityLiveBinding
import com.kyzh.core.databinding.TabLiveBinding
import com.kyzh.core.utils.loadGif
import com.kyzh.core.utils.loadImage
import com.kyzh.core.utils.setVisibility
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.activity_answer.*
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.net.URL

class LiveActivity : BaseActivity() {
    companion object {
        @JvmStatic
        fun start(context: Context, roomId: String) {
            val starter = Intent(context, LiveActivity::class.java).putExtra("roomId", roomId)
            context.startActivity(starter)
        }
    }

    private val tabs = arrayListOf("聊天",  "排行")
    private var binding: ActivityLiveBinding? = null
    private var roomId: String = ""
    private var roomInfo: LiveRoomInfo? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AView.setStatusBar(this,false)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_live)
        binding?.video?.setMargins(0, AView.getStatusBarHeight(this), 0, 0)
        binding?.initView()
    }

    fun ActivityLiveBinding.initView() {
        roomId = intent.getStringExtra("roomId")
        // 注册监听关闭指令
        LiveEventBus.get<Int>("closeRoom").observe(this@LiveActivity){
            exit()
        }
        LiveRequest.geiLiveInfo(roomId) {
            roomInfo = this
            this?.apply {
                initVideo(play_url, name,hot)
                initUser(this)
                initTab(this)
                initSvga()
            }
        }
    }
    private fun ActivityLiveBinding.initSvga(){
        LiveEventBus.get<RoomGift>("RoomGift").observe(this@LiveActivity){
            Log.e(SendGiftItemFragment.TAG, "initSvga: "+it )
            if(it==null){

            }else{
                if (it.img_type== "2"){
                    ivSvg.clear()
                    ivSvg.setVisibility(true)

                    SVGAParser(this@LiveActivity).decodeFromURL(URL(it.img),object : SVGAParser.ParseCompletion {
                        override fun onComplete(videoItem: SVGAVideoEntity) {
                            ivSvg.setVideoItem(videoItem);
                            ivSvg.stepToFrame(0, true);
                            lifecycleScope.launch {
                                delay((it.time * 1000).toLong())
                                runOnUiThread {
                                    ivSvg.setVisibility(false)
                                }
                            }
                        }
                        override fun onError() {
                            ivSvg.setVisibility(false)
                        }
                    })
                }else{
//                    val drawable = ivShowGif.drawable
//                    if (drawable!= null && drawable is BitmapDrawable) {
//                         drawable as Bitmap
//                        drawable.recycle();
//                    }
                    ivShowGif.setImageBitmap(null);
                    ivShowGif.setVisibility(true)
                    if (it.img_type == "0") ivShowGif.loadImage(this@LiveActivity,it.icon) else ivShowGif.loadGif(it.img)
                    lifecycleScope.launch {
                        // 注意礼物设置0秒了  不显示  可恶 查了半天不显示图得原因
                        delay((it.time * 1000).toLong())
                        runOnUiThread {
                            ivShowGif.setVisibility(false)
                        }
                        cancel()
                    }
                }

            }
        }
    }
    private fun ActivityLiveBinding.initVideo(playUrl: String, name: String,hot :String) {

        video.apply {

            isNeedShowWifiTip = false
            dismissControlTime = 2000
            setIsTouchWiget(true)
            setThumbPlay(true)
            tvHot.text = hot
            startButton.setVisibility(false)
            backButton.setOnClickListener {
                if (video.isIfCurrentIsFullscreen) {
                    GSYVideoManager.backFromWindowFull(context)
                } else {
                    exit()
                }

            }

            isLockLand = true;
            isAutoFullWithSize = false
            isShowFullAnimation = true;
            fullscreenButton.setOnClickListener {
                backButton.visibility = View.VISIBLE
                startWindowFullscreen(context, true, true)
            }
            startButton.setOnClickListener {
                when (currentState) {
                    GSYVideoView.CURRENT_STATE_PAUSE -> {
                        onVideoResume(false)
                    }
                    GSYVideoView.CURRENT_STATE_PLAYING -> {
                        onVideoPause()
                    }
                    else -> {
                        startPlayLogic()
                    }
                }
            }
            isAutoFullWithSize = false
            isShowFullAnimation = true;

            setVideoAllCallBack(object : GSYSampleCallBack() {
                override fun onPrepared(url: String?, vararg objects: Any?) {
                    super.onPrepared(url, *objects)
                    val full: Boolean =
                        video.isIfCurrentIsFullscreen()
                    if (!video
                            .isIfCurrentIsFullscreen()
                    ) {
                    }
                    if (video.isIfCurrentIsFullscreen()) {
                        GSYVideoManager.instance().setLastListener(video)
                    }
                }

                override fun onEnterFullscreen(url: String?, vararg objects: Any?) {
                    super.onEnterFullscreen(url, *objects)
                }

                override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                    super.onQuitFullscreen(url, *objects)
                }
            })
        }
        video.setUp(playUrl, true, name)
        video.startPlayLogic()
    }

    //用户页
    private fun ActivityLiveBinding.initUser(data1: LiveRoomInfo) {
        data = data1
        if(data1.is_guanzhu == 0){
            mbtCollect.text = "订阅"
        }else{
            mbtCollect.text = "已订阅"
        }
        mbtCollect.setOnClickListener {
            LiveRequest.liveGuanzhu(roomId){
                if(this != 1){
                    mbtCollect.setVisibility(true)
                }else{
                    if(mbtCollect.text == "已订阅"){
                        mbtCollect.text = "订阅"
                    }else{
                        mbtCollect.text = "已订阅"
                    }
                }
            }
        }
    }

    // tab设置
    fun ActivityLiveBinding.initTab(data1: LiveRoomInfo) {
        viewpage.adapter = object : FragmentStateAdapter(this@LiveActivity) {
            override fun getItemCount() = tabs.size

            override fun createFragment(position: Int): Fragment {
                return when (position) {
                    0 -> LiveChatFragment.newInstance(data1)
//                    1 -> LiveUserFragment.newInstance()
                    1 -> LiveSortFragment.newInstance(data1.room_id)
                    else -> LiveChatFragment.newInstance(data1)
                }
            }
        }
        viewpage.offscreenPageLimit = OFFSCREEN_PAGE_LIMIT_DEFAULT
        val tabLayoutMediator = TabLayoutMediator(tab, viewpage ,true,false,) { tab, p ->
            tab.text = tabs[p]
            tab.customView = null
            TabLiveBinding.inflate(layoutInflater).apply {
                title.text = tab?.text
                title.textSize = 16f
                tab?.customView = root
            }
        }
        tab.post {
            tab.getTabAt(0)?.select()
        }
        tabLayoutMediator.attach()
        tab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.customView = null
                TabLiveBinding.inflate(layoutInflater).apply {
                    title.text = tab?.text
                    ivLine.setVisibility(true)
                    title.textSize = 16f
                    title.setTextColor(Color.parseColor("#FFF77105"))
                    tab?.customView = root

                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.customView = null
                TabLiveBinding.inflate(layoutInflater).apply {
                    title.text = tab?.text
                    title.textSize = 14f
                    ivLine.visibility = View.INVISIBLE
                    tab?.customView = root
                }
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
                tab?.customView = null
                TabLiveBinding.inflate(layoutInflater).apply {
                    title.text = tab?.text
                    title.textSize = 16f
                    ivLine.setVisibility(true)
                    title.setTextColor(Color.parseColor("#FFF77105"))
                    tab?.customView = root

                }
            }

        })
    }

    override fun onBackPressed() {
        exit()
    }

    // 退出逻辑     主播得话就关闭页面  其他人退出群聊
    fun exit() {
        if (binding?.video!!.isIfCurrentIsFullscreen) {
            GSYVideoManager.backFromWindowFull(this)
        } else {
            if (uid == roomInfo?.supadmin_uid) {
                finish()
            } else {
                V2TIMManager.getInstance().quitGroup(roomId, object : V2TIMCallback {
                    override fun onSuccess() {
                        runOnUiThread {
                            finish()
                        }
                    }
                    override fun onError(p0: Int, p1: String?) {
                        runOnUiThread {
//                            "退出失败".toast()
                            finish()
                        }

                    }
                })
            }
        }
    }
}